<template>
    <!--        <a-tooltip :title="hoverText" :visible="displayTooltip" placement="top"></a-tooltip>-->
    <!--        @popupScroll="onPopupScroll"-->
    <!--    @search="handleSearch"-->

    <a-select
        v-bind="$attrs"
        v-on="listeners"
        show-search
        :placeholder="placeholder"
        :optionFilterProp="optionFilterProp"
        v-model="currentValue"
        allowClear
        :filter-option="filterOption"
    >
        <a-icon v-if="fetching" style="color: #096dd9" slot="suffixIcon" type="loading" />
        <a-spin v-if="fetching" slot="notFoundContent" size="small" />
        <a-select-option v-for="i in list" :key="i.userId" :value="i.userId">
            {{ displayValue(i) }}
        </a-select-option>
    </a-select>
</template>
<script>
/*
*  @mouseenter="mouseEnter(i)"
                             @mouseleave="hoverText = ''"
* */
import { getOrgEmployeesListBy, getOneOrgUsers } from '@/api/commons'
import debounce from 'lodash/debounce'

/*
*
* 一次性查数据太多了，会卡
* 优化版的src/components/Select/ASelectOrgPeople.vue
*
*
* */
export default {
    inheritAttrs: false,
    name: 'SelectOrgPeople',
    props: {
        // v-model绑定的数据
        value: {
            type: [Array, String, Object]
        },
        // 组织id
        orgId: [String, Number, Object],
        // 组织ids
        orgIds: {
            type: [Array, String]
        },
        isArray: {
            type: Boolean,
            default: () => false
        },
        api: {
            type: [Object, Function],
            default: () => getOneOrgUsers
        },
        //同一个页面区分组件valueKey
        valueKey: {
            type: String,
            default: () => ''
        },
        // 需要联动的表单名
        keyValue: {
            type: String,
            default: () => 'test'
        },
        form: {
            type: Object,
            default: () => ({})
        },
        // placeholder
        placeholder: {
            type: String,
            default: () => '请选择'
        },
        // 搜索时过滤对应的 option 属性，如设置为 children 表示对内嵌内容进行搜索,否则为value
        optionFilterProp: {
            type: String,
            default: () => 'children'
        },
        // 是否初始化
        init: {
            type: Boolean,
            default: () => false
        },
        // orgId是否不能为空，为空不请求
        isOrgIdNotNull: {
            type: Boolean,
            default: () => false
        },
        isAutoSelectMe: {
            type: Boolean,
            default: () => false
        },
        // 自定义name
        customRender: {
            type: [Function],
            default: null
        },
        validEmpty: {
            type: Boolean,
            default: false
        },
        // 请求参数
        requestParams: {
            type: Object,
            default: () => ({})
        },
        // 是否是搜索框，如果是的话，orgId改变会清空当前值
        isSearch: {
            type: Boolean,
            default: () => false
        }
    },
    data() {
        //防抖
        this.handleSearch = debounce(this.handleSearch, 800)
        return {
            fetching: false,
            list: [],
            total: 0,
            pageNumber: 1,
            pageSize: 10,
            queryParams: {},
            hoverText: '',
        }
    },
    watch: {
        attr(e) {
            // console.log(e)
            //如果是禁用的状态下，那么更改了orgId，把 this.currentValue 设为underfined，
            //具体使用场景了， 资产调拨的搜索框需要默认值
            if (this.isSearch){
                this.currentValue = undefined
            }
            if (!e) {
                if (this.isOrgIdNotNull) return this.list = []
            }
            this.reset()
        },
        orgIds() {
            if (arguments[0]?.toString() == arguments[1]?.toString()) {
                return
            }
            console.log('orgIds')
            this.getList()
        }
    },

    mounted() {
        this.init && this.getList()
    },
    methods: {
        mouseEnter(i) {
            this.hoverText = this.displayValue(i)
        },
        displayValue(i) {
            //customRender ? customRender(i) : i.name
            return this.customRender ? this.customRender(i) : i.name
        },
        reset() {
            this.queryParams = {}
            this.pageNumber = 1
            this.getList()
        },
        filterOption(input, option) {
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            )
        },
        handleSearch(value) {
            this.queryParams.nameLike = value
            this.pageNumber = 1
            this.getList(true)
        },
        onPopupScroll(e) {
            const { target } = e
            if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
                if (this.fetching) return
                if (this.total / this.pageSize > this.pageNumber) {
                    this.pageNumber = this.pageNumber + 1
                    this.getList()
                }
            }
        },
        async getList(isSearch = false) {
            let params = {}
            if (!this.isArray) {
                if (this.validEmpty && !this.attr) {
                    this.list = []
                    this.$emit('changePersonNumber', this.list?.length)
                    this.total = 0
                    return
                }
                params = {
                    // pageSize: this.pageSize,
                    pageSize: 999999,
                    pageNumber: 1,
                    // pageNumber: this.pageNumber,
                    ...this.queryParams,
                    orgPath: this.attr
                }
            } else {
                if (!this.orgIds || this.orgIds?.length == 0) {
                    this.list = []
                    this.$emit('changePersonNumber', this.list.length)
                    return
                }
                isSearch = true
                params = {
                    pageSize: 999999,
                    pageNumber: 1,
                    ...this.queryParams,
                    query: {
                        rootOrgIds: typeof this.orgIds == 'string' ? [this.orgIds] : this.orgIds
                    },
                    rootOrgIds: this.orgIds
                }
            }

            this.fetching = true
            // 添加额外参数
            if (Object.keys(this.requestParams)?.length > 0) {
                params = Object.assign({}, params, this.requestParams)
            }
            let res = await this.api(params)
            this.fetching = false
            if (res) {
                if (isSearch) {
                    this.list = res.list || res.data
                } else {
                    this.list = res.list || res.data
                    // this.list = this.list.concat(res.list)
                }
                if (this.isAutoSelectMe) {
                    let res2 = this.list.find(v => v.userId === this.$userInfo().id)
                    if (res2) {
                        this.currentValue = res2.userId
                    }
                }
                this.$emit('changePersonNumber', this.list?.length)
                this.total = res.total
            }
        }
    },
    computed: {
        listeners() {
            let listeners = this.$listeners
            delete listeners.search
            return listeners
        },
        displayTooltip() {
            return this.hoverText.length > 10
        },
        // 需要联动的表单值
        attr() {
          let attrValue
          const keys = this.keyValue.split('.')
          const findValueFromKeys = (data, key) => {
            if(data instanceof Object && keys.some(k => k === key)){
              return findValueFromKeys(data[key], keys[keys.findIndex(k => k === key) + 1])
            }
            return data
          }
          if(keys && !!keys.length){
            attrValue = findValueFromKeys(this.form, keys[0])
          }
          return attrValue || this.orgId
            // if (this.form[this.keyValue]) {
            //     return this.form[this.keyValue]
            // }
            // return this.orgId
        },
        // 转换绑定的选中数据，与v-model同步
        currentValue: {
            get: function() {
                return this.value
            },
            set: function(value) {
                // console.log(value)
                this.$emit('input', value)
                this.$emit('change', value)
                // console.log(this.list.find((v) => v.userId === value))
                let res = this.list.find((v) => v.userId === value)
                if (res) {
                    res.key = this.valueKey
                    this.$emit('onSelectChange', res)
                } else {
                    this.$emit('onSelectChange', {})
                }
            }
        }
    }
}
</script>
